<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="staffDate.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="inp"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="tree"
          :default-expand-all="true"
          :data="depts"
          :props="defaultProps"
          :expand-on-click-node="false"
          node-key="id"
          :highlight-current="true"
          :check-strictly="true"
          @current-change="hCurrentChange"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button size="mini" type="primary" @click="$router.push('/detail')">添加员工</el-button>
          <el-button v-allow="'excel_import'" size="mini" @click="employeeExcel=true">excel导入</el-button>
          <el-button v-allow="'excel_export'" size="mini" @click="derive">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="list">
          <el-table-column align="center" label="头像">
            <template slot-scope="{ row }">
              <img v-if="row.staffPhoto" style="width:30px" :src="row.staffPhoto" alt="">
              <span v-else class="username">{{ row.username.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column label="聘用形式">
            <template slot-scope="{ row }">
              {{ row.formOfEmployment===1 ? '正式' : (row.formOfEmployment===2 ? '非正式' : '未知') }}
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template slot-scope="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="character(row.id)">角色</el-button>
              <el-popconfirm title="确认删除该行数据吗？" @onConfirm="confirmDel(row.id)">
                <el-button slot="reference" style="margin-left:10px" size="mini" type="text">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <!--放置分页组件
                total：总数据条数
                page-size:每页几条数据
                @current-change:页码变化（用户点击）执行，自动传入当前的页码
                @current-change="hCurrentChage"
                @size-change="hSizeChange"-->
          <el-pagination
            :current-page="staffDate.page"
            :page-sizes="[3,5,7]"
            :background="true"
            layout="prev, pager, next, sizes"
            :total="total"
            :page-size="staffDate.pagesize"
            @size-change="hSizeChange"
            @current-change="hPagination"
          />
        </el-row>
      </div>
    </div>
    <!-- 导出 -->
    <import-excel :employee-excel.sync="employeeExcel" @uploadSuccess="getStaff" />
    <!-- 角色弹窗 -->
    <assign-role
      ref="refRole"
      :is-dialog.sync="isDialog"
      :character-id="characterId"
    />
  </div>
</template>

<script>
import { getEmployee, deriveData, delEmployee } from '@/api/employee'
import { getDepartment } from '@/api/department'
import { arrTree } from '@/utils'
import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
import { Message } from 'element-ui'
import assignRole from './components/AssignRole.vue'
export default {
  name: 'Employee',
  components: { importExcel, assignRole },
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      staffDate: {
        page: 1,
        pagesize: 5,
        keyword: null,
        departmentId: null
      },
      total: 0,
      list: [],
      // sous
      search: '',
      employeeExcel: false,
      // 删除的开关
      isShow: false,
      // 角色弹窗开关
      isDialog: false,
      characterId: -1
    }
  },
  created() {
    this.getDepartments()
  },
  methods: {
    // 角色
    character(id) {
      // 开启弹窗
      this.isDialog = true
      // 将获取到的id赋值传给子组件
      this.characterId = id
      // 调用子组件的请求方法
      this.$nextTick(() => {
        this.$refs.refRole.getRoleById()
      })
    },
    // 搜索
    inp() {
      // 关闭定时器
      clearTimeout(this.time)
      // 设置防抖 节约性能
      this.time = setTimeout(() => {
        // 发请求 从第一页开始查找
        this.staffDate.page = 1
        // 重新渲染
        this.getStaff()
      }, 500)
      // console.log(this.search)
    },
    // 获取-部门列表
    async getDepartments() {
      const res = await getDepartment()
      // console.log(res.data)
      this.depts = arrTree(res.data, 0)
      this.$nextTick(() => {
        // this.$refs.tree.setCheckedKeys([this.depts[0].id])
        // 页面加载显示高亮
        this.$refs.tree.setCurrentKey(this.depts[0].id)
      })
      // 获取信息先将id赋值
      this.staffDate.departmentId = this.depts[0].id
      // 页面一加载就要发一次请求
      this.getStaff()
    },
    // 获取列表信息
    async getStaff() {
      // console.log('111')
      // axios在发请求的时候，如果你的参数值为null,它会丢弃这个参数
      // 发请求拿数据
      const res = await getEmployee(this.staffDate)
      // 赋值
      this.total = res.data.total
      this.list = res.data.rows
      // console.log(res)
    },
    hCurrentChange(data, node) {
      this.staffDate.departmentId = data.id
      this.getStaff()
    },
    // 页码
    hPagination(page) {
      // 更改页码
      this.staffDate.page = page
      // 重新发请求
      this.getStaff()
    },
    // 每页条数
    hSizeChange(val) {
      // console.log(`每页 ${val} 条`)
      // 更新每页显示的条数
      this.staffDate.pagesize = val
      // 更新之后跳转到第一页
      this.staffDate.page = 1
      // 重新发请求
      this.getStaff()
    },
    // 导出
    async derive() {
      const res = await deriveData()
      // console.log(res)
      FileSaver.saveAs(res, '员工信息表.xlsx') // 下载文件
    },
    // 删除功能
    async confirmDel(id) {
      const res = await delEmployee(id)
      // console.log(res.message)
      // 提示用户
      Message.success(res.message)
      // 重新渲染
      this.getStaff()
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
  }
}

</style>
<style>
.el-tree--highlight-current .el-tree-node.is-checked > .el-tree-node__content {
    color: #276FFB;
    background-color: #f0f4ff;
}
</style>
